<template>
  <div class="message-container" ref="message-container">
    <MessageArea title="留言板" :subTitle="`(${data.total})`" v-loading="isLoading" :list="data.rows"
      :isListLoading="isLoading" @submit="handleSubmit" />
    <noMore v-if="show" />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import * as msgApi from "@/api/message.js";
import mainScroll from "@/mixins/mainScroll.js";
import noMore from '@/components/noMore';
export default {
  mixins: [fetchData({ total: 0, rows: [] }), mainScroll("message-container")],
  components: {
    MessageArea,
    noMore,
  },
  data() {
    return {
      page: 1,
      limit: 10,
      show: false,
    }
  },
  created() {
    // 监听主区域
    this.$bus.$on('mainScroll', this.handleScroll);
  },
  destroyed() {
    // 取消监听
    this.$bus.$off('mainScroll', this.handleScroll);
  },
  computed: {
    hasMore() {
      return this.data.rows.length < this.data.total;
    },
  },
  methods: {
    async fetchData() {
      return await msgApi.getMessages(this.page, this.limit);
    },
    // 处理滚动事件
    handleScroll(dom) {
      if (this.isLoading || !dom) {
        // 正在加载，什么也不干
        return;
      }
      const range = 100;
      // 差值 = 元素滚动条高度
      const dec = Math.abs(dom.scrollTop + dom.clientHeight - dom.scrollHeight);
      if (dec < range) {
        this.fetchNext();
      }
    },
    // 加载下一页
    async fetchNext() {
      if (!this.hasMore) {
        // 没有更多数据就不在继续请求
        // 同时显示没有更多数据了
        this.show = true;
        return;
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.isLoading = false;
    },
    async handleSubmit(data, callback) {
      const resp = await msgApi.postMessages(data);
      callback("留言成功");
      this.data.rows.unshift(resp);
    },
  },

}
</script>

<style lang="less" scoped>
.message-container {
  height: 100%;
  width: 100%;
  overflow-y: auto;
  box-sizing: border-box;
  padding: 25px 0;
  scroll-behavior: smooth;
  position: relative;
}

.message-area-container {
  width: 700px;
  margin: 0 auto;
  // position: relative;
}
</style>